package com.ddpt.platform.common.util;

import com.ddpt.platform.common.enums.LogLevel;
import com.ddpt.platform.common.exception.CommonException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/** 日志 */
@Component
public class LoggerUtil {

	//保存tranceId
	private static final ThreadLocal<String> tranceId = new ThreadLocal<>();

	/** 项目名 */
	private static final String baseName = "marketing";

	private static LoggerPrintInterceptor loggerPrintInterceptor;

	private static String getPre(){
		return "["+baseName+"-"+System.getProperty("project.name")+"]["+getTranceId()+"]>>>";
	}

	public static void debug(Class<?> clazz, String str, Object... objs) {
		if(loggerPrintInterceptor!=null && !loggerPrintInterceptor.isPrint(LogLevel.DEBUG,clazz,str,objs)){
			return ;
		}
		compelDebug(clazz, str, objs);
	}

	public static void compelDebug(Class<?> clazz, String str, Object... objs){
		str = str == null ? "" : str;
		LoggerFactory.getLogger(clazz).debug(getPre() + str, objs);
	}

	public static void info(Class<?> clazz, String str, Object... objs) {
		if(loggerPrintInterceptor!=null && !loggerPrintInterceptor.isPrint(LogLevel.INFO,clazz,str,objs)){
			return ;
		}
		compelInfo(clazz, str, objs);
	}

	public static void compelInfo(Class<?> clazz, String str, Object... objs){
		str = str == null ? "" : str;
		LoggerFactory.getLogger(clazz).info(getPre() + str, objs);
	}

	public static void warn(Class<?> clazz, String str, Object... objs) {
		if(loggerPrintInterceptor!=null && !loggerPrintInterceptor.isPrint(LogLevel.WARN,clazz,str,objs)){
			return ;
		}
		compelWarn(clazz, str, objs);
	}

	public static void compelWarn(Class<?> clazz, String str, Object... objs){
		str = str == null ? "" : str;
		LoggerFactory.getLogger(clazz).warn(getPre() + str, objs);
	}

	public static void error(Class<?> clazz,Throwable e, String str) {
		str = str == null ? "" : str;
		LoggerFactory.getLogger(clazz).error(getPre() + str, e);
	}

	public static void error(Class<?> clazz, Throwable e) {
		error(clazz,e, "");
	}

	public static void error(Class<?> clazz,String str){
		error(clazz,new CommonException(str));
	}

	public static void setTranceId(String tranceId) {
		LoggerUtil.tranceId.set(tranceId);
	}

	public static String getTranceId() {
		if(tranceId.get() == null){
			tranceId.set(UUID.randomUUID().toString().replace("-",""));
		}
		return tranceId.get();
	}

	public static void clearTransId(){
		tranceId.remove();
	}

	@Autowired(required = false)
	public void setLoggerPrintInterceptor(LoggerPrintInterceptor loggerPrintInterceptor) {
		LoggerUtil.loggerPrintInterceptor = loggerPrintInterceptor;
	}
}
